//
//  UIImage+GQHGIF.m
//  Seed
//
//  Created by GuanQinghao on 06/02/2018.
//  Copyright © 2018 GuanQinghao. All rights reserved.
//

#import "UIImage+GQHGIF.h"
#import <ImageIO/ImageIO.h>

@implementation UIImage (GQHGIF)

+ (UIImage *)qh_animateGIFWithData:(NSData *)data {
    
    if (!data) {
        
        return nil;
    }
    
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    size_t count = CGImageSourceGetCount(source);
    
    UIImage *gifImage;
    if (count <= 1) {
        
        gifImage = [[UIImage alloc] initWithData:data];
    } else {
        
        NSMutableArray *imageArray = [NSMutableArray array];
        NSTimeInterval duration = 0.0f;
        
        for (size_t i = 0; i < count; i++) {
            
            CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);
            if (!image) {
                
                continue;
            }
            
            duration += [self durationAtIndex:i source:source];
            [imageArray addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];
            CGImageRelease(image);
        }
        
        if (!duration) {
            
            duration = (1.0f / 10.0f) * count;// ?
        }
        
        gifImage = [UIImage animatedImageWithImages:imageArray duration:duration];
    }
    CFRelease(source);
    
    return gifImage;
}

+ (float)durationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source {
    
    float duration = 0.1f;
    
    CFDictionaryRef propertiesCF = CGImageSourceCopyPropertiesAtIndex(source, index, nil);
    NSDictionary *properties = (__bridge NSDictionary *)propertiesCF;
    NSDictionary *gifProperties = properties[(NSString *)kCGImagePropertyGIFDictionary];
    
    NSNumber *unclampedDelayTime = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime];
    if (unclampedDelayTime) {
        
        duration = [unclampedDelayTime floatValue];
    } else {
        
        NSNumber *delayTime = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime];
        if (delayTime) {
            
            duration = [delayTime floatValue];
        }
    }
    
    // Many annoying ads specify a 0 duration to make an image flash as quickly as possible. We follow Firefox's behavior and use a duration of 100 ms for any frames that specify a duration of <= 10 ms. See <rdar://problem/7689300> and <http://webkit.org/b/36082> for more information.
    if (duration < 0.011f) {
        
        duration = 0.100f;
    }
    CFRelease(propertiesCF);
    
    return duration;
}

@end
